package comm;

import java.io.InputStream;

import td.game.Main;
import td.game.MainGamePanel;
import android.os.Handler;
import android.util.Log;

/** Thread that keeps listening for incoming messages.
 * 
 * @author Bruno Zumba (27/09/2011)
 *
 */
public class ReceivingThread extends Thread {
	private final String TAG = ReceivingThread.class.getSimpleName();
	
	private InputStream input;
	private Handler outsideHandler; //Handler that handles the arrived message
	
	private boolean running;
	
	public ReceivingThread(InputStream input, Handler outsideHandler){
		this.input = input;
		this.outsideHandler = outsideHandler;
		
		running = true;
	}
	
	public void setRunning(boolean running){
		this.running = running;
	}
	
	public void run(){
		byte[] buffer;
		int size;
		
		
		
		
		while(running){
			buffer = new byte[1000];
    		size = 0;
    		
	    	try {
				Log.i(TAG, String.valueOf("Ready to read"));
				size = input.read(buffer);

			} catch (Exception e) {
				Log.i(TAG, "Couldn't read from input buffer. Size: "+size, e);
			}
			if(size == -1){
		    	byte[] bArray = "Socket to the Framework was closed.".getBytes();
		    	Log.i(TAG, "envando pro mngmpn. Length do bArray: "+bArray.length);
				outsideHandler.obtainMessage(MainGamePanel.ERROR_MESSAGE_ARRIVED, bArray.length, Main.KILL_APP, bArray).sendToTarget();
		    	setRunning(false);
			} else {

	    	//MainGamePanel.OUTSIDE_MESSAGE is useless so far.
				outsideHandler.obtainMessage(MainGamePanel.MESSAGE_ARRIVED, size, -1, buffer).sendToTarget();
			}
		}
	}

}
